package com.linkcard.list.action;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.linkcard.commen.tools.Helper;
import com.linkcard.commen.tools.Page;
import com.linkcard.list.manager.CategoryManager;
import com.linkcard.list.manager.NewsManager;
import com.linkcard.list.model.Category;
import com.linkcard.list.model.News;
import com.linkcard.user.model.User;
import com.linkcard.user.model.WebsiteColumns;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class NewsAction extends ActionSupport {

	private NewsManager newsManager=null;
	private CategoryManager categoryManager=null;
	private News news=null;
	private int page;
	private int rows;
	private Page pageObj=null;
	private String searchStr=null;
	private String ids=null;
	private int columnId;
	private List list=null;
	private List categoryList=null;
	private String path=null;
	@Override
	public String execute() throws Exception {
		pageObj=new Page();
		pageObj.setCurrentPage(page);
		pageObj.setPageSize(20);
		list=this.newsManager.newsList(pageObj,(searchStr==null)?"":searchStr);
		categoryList=this.categoryManager.categoryListBySelect(4,-1);
		WebsiteColumns column=null;
		List columnList=(List)ActionContext.getContext().getApplication().get("columns");
		for(int i=0;i<columnList.size();i++)
		{
			 column=(WebsiteColumns)columnList.get(i);
			if(column.getId()==4)
			{
				path="<a href='"+column.getUrl()+".action?columnId="+column.getId()+"'>"+column.getName()+"</a>";
				break;
			}
		}
		if(searchStr==null)
		{
		     path+=">>所有信息";
		     path="<span>位置："+path+"</span><h1>新闻中心</h1>";
		}else
		{
			String[] cids=searchStr.split("_");
			path+=">><a href='news.action?page=1&searchStr="+cids[0]+"_-2_'>"+categoryManager.findCategory(Integer.parseInt(cids[0])).getName()+"</a>";
		    if(!cids[1].equals("-2"))
		    {
		    	path+=">><a href='news.action?page=1&searchStr="+searchStr+"'>"+categoryManager.findCategory(Integer.parseInt(cids[1])).getName()+"</a>";
		    }
		    path="<span>位置："+path+"</span><h1>"+categoryManager.findCategory(Integer.parseInt(cids[0])).getName()+"</h1>";
		}
		return "success";
	}
	//添加新闻
	public String addNews() throws Exception{
		this.clearMessages();
		@SuppressWarnings("unused")
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		User user=(User)ActionContext.getContext().getSession().get("user");
		news.setRecommend((news.getRecommend()==null)?0:news.getRecommend());
		news.setDatetime(sdf.format(new Date()));
		news.setPublisher(user.getId());
		boolean isSuccess=this.newsManager.addNews(news);
		if(isSuccess)
		{
			this.addActionMessage("添加成功!");
		}else
		{
			this.addActionMessage("添加失败!");
			return "AddNew";
		}
		return "NewsList";
	}
	//获得新闻列表
	public String newsListForJson()throws Exception{
		pageObj=new Page();
		pageObj.setCurrentPage(page);
		pageObj.setPageSize(rows);
		JSONObject json=new JSONObject();
		JSONArray jsonArray=new JSONArray();
		searchStr=Helper.decode(searchStr);
		List list=this.newsManager.newsList(pageObj,this.searchStr);
		for(int i=0;i<list.size();i++)
		{
			Object[] objs=(Object[])list.get(i);
			News news=(News)objs[0];
			User user=(User)objs[1];
			Category category=(Category)objs[2];
			Category subCategory=categoryManager.findCategory(news.getSubCategoryId());
			JSONObject tempjson=new JSONObject();
			tempjson.put("id", news.getId());
			tempjson.put("title", news.getTitle());
			tempjson.put("category",category.getName());
			tempjson.put("subcategory",(subCategory!=null)?subCategory.getName():"");
			tempjson.put("datetime",news.getDatetime());
			tempjson.put("recommend",(news.getRecommend()==0)?"否":"是");
			tempjson.put("opt", "<a href='news!newsDetial.action?news.id="+news.getId()+"'target='_blank'>查看</a>&nbsp;&nbsp;<a href='news!modifyPage.action?news.id="+news.getId()+"&columnId="+columnId+"' >修改</a>&nbsp;&nbsp;<a href='javascript:void(0);' onclick='deleteNews("+news.getId()+")'>删除</a>");
			jsonArray.add(tempjson);
		}
		json.put("total", pageObj.getRowCount());
		json.put("rows", jsonArray);
		backText(json.toString());
		return "Data";
	}
	//修改页面
	public String modifyPage()throws Exception {
		this.clearMessages();
		news=this.newsManager.findNews(news.getId());
		return "ModifyPage";
	}
	public String modifyNews() throws Exception{
		news.setRecommend((news.getRecommend()==null)?0:news.getRecommend());
		boolean isSuccess=this.newsManager.modifyNews(news);
		if(isSuccess)
		{
			this.addActionMessage("修改成功!");
		}else
		{
			this.addActionMessage("修改失败!");
			return "ModifyPage";
		}
		return "NewsList";
	}
	//删除新闻
	public String deleteNews() throws Exception{
		//ids
		boolean isSuccess=this.newsManager.deleteNews(ids);
		JSONObject json=new JSONObject();
		json.put("info", isSuccess);
		 backText(json.toString());
		return "Data";
	}
	//单个新闻
	public String newsDetial() throws Exception{
		news=this.newsManager.findNews(news.getId());
		categoryList=this.categoryManager.categoryListBySelect(4,-1);
		WebsiteColumns column=null;
		List columnList=(List)ActionContext.getContext().getApplication().get("columns");
		for(int i=0;i<columnList.size();i++)
		{
			 column=(WebsiteColumns)columnList.get(i);
			if(column.getId()==4)
			{
				path="<a href='"+column.getUrl()+".action?columnId="+column.getId()+"'>"+column.getName()+"</a>";
				break;
			}
		}
		Category category=categoryManager.findCategory(news.getCategoryId());
		path+=">><a href='news.action?page=1&searchStr="+category.getId()+"_-2_'>"+category.getName()+"</a>";
	    if(news.getSubCategoryId()!=-2)
	    {
	    	Category subCategory=categoryManager.findCategory(news.getSubCategoryId());
	    	path+=">><a href='news.action?page=1&searchStr="+category.getId()+"_"+subCategory.getId()+"_'>"+subCategory.getName()+"</a>";
	    }
		return "NewsDetial";
	}
	//返回文本
	public void backText(String data) throws Exception
	{
		ServletActionContext.getResponse().setContentType ("text/html;charset=utf-8");
		
		  PrintWriter out = ServletActionContext.getResponse().getWriter();
		  out.print(data);
		  out.flush();
		  out.close();
	}
	public NewsManager getNewsManager() {
		return newsManager;
	}
	public void setNewsManager(NewsManager newsManager) {
		this.newsManager = newsManager;
	}
	public News getNews() {
		return news;
	}
	public void setNews(News news) {
		this.news = news;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	public Page getPageObj() {
		return pageObj;
	}
	public void setPageObj(Page pageObj) {
		this.pageObj = pageObj;
	}
	public String getSearchStr() {
		return searchStr;
	}
	public void setSearchStr(String searchStr) {
		
		this.searchStr = searchStr;
	
	}
	public CategoryManager getCategoryManager() {
		return categoryManager;
	}
	public void setCategoryManager(CategoryManager categoryManager) {
		this.categoryManager = categoryManager;
	}
	public void setIds(String ids) {
		this.ids = ids;
	}
	public int getColumnId() {
		return columnId;
	}
	public void setColumnId(int columnId) {
		this.columnId = columnId;
	}
	public List getList() {
		return list;
	}
	public void setList(List list) {
		this.list = list;
	}
	public List getCategoryList() {
		return categoryList;
	}
	public void setCategoryList(List categoryList) {
		this.categoryList = categoryList;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}

}
